var timeline = new function(){
	
	var	  _timeline = null
		, _sequences = []
		, _$wrapperBox = null
		, _$addButton =  null
	;
	
	
	//Templates
	var _TMPL_timeline = '<div></div>';
	var _TMPL_sequence = '<div class="sequence"><div class="toolbar"><input type="numeric" class="repeatSequence" style="width:50px; /*margin-top:-15px;*/" value="0" /><a class="deleteSequence" title="Eliminar secuencia"><img src="/img/trash.png" /></a></div><div class="sequenceContainer"><a class="addAction" title="Añadir acción"><img src="/img/new_action.png" /></a></div></div>';
	var _TMPL_action = '<div class="actions"><a class="edit-action" title="modify this action"></a><a class="delete-action"><img src="/img/red_cross.png" /></a></div>';

	//Guarda el objeto seleccionado al ir a la ventana de previsualización
	_lastSelectedObject = false; 
	
	
	function _init(){
		
		_$wrapperBox = $("#wrapperBox");
		_$addButton = $("#addSequence");
		

		_$addButton.click(function(){
			
			//No se añade una nueva secuencia si la última secuencia está aún vacía
			if (!_$wrapperBox.find('.sequence').length || _$wrapperBox.find('.sequence').last().find('.actions').length){
				_addSequence();	
			}
				
		});
		
		//export button
		$('#show-timeline').click(function(){
			
			if(mainCanvas.canvas.getActiveGroup()){
				alert('No se puede asociar eventos a un grupo de objetos.')
			}
			else if (!mainCanvas.canvas.getActiveObject()){
				alert('No hay ningún objeto seleccionado.')
			}
			else {
				var object = leftTree.selected().text;
				$("#timeline-window").data("kendoWindow").title('Timeline del objeto ' + object)
				$("#timeline-window").data("kendoWindow").center().open();
				
				
				_updateSequencesList();
			}
							
			mainCanvas.canvas.getActiveObject()
		});
		
		$("#okTimeline").click(function(){
			$("#timeline-window").data("kendoWindow").close();
		});
		
		$('#timeline').on('click', '.edit-action', function(event){
			
			_editAction(this);
		})
		
		$('#timeline').on('click', '.delete-action', function(event){
			
			_deleteAction(this);
		})
		
		$('#timeline-preview').on('click', function(){
			
			_lastSelectedObject = leftTree.selected().uid;
			$("#timeline-window").data("kendoWindow").close();
			previewController.open();
		})
		
		_hide();
		
		
	}//end _init function
	
	
	function _editAction(obj){
		
		var actionID = $(obj).parent().attr('id');
		var action = leftTree.getAction(actionID);
		
		if (!action){
			window.console.log('ERROR. Ninguna acción con el identificador ' + actionID);
			return false;
		}
		
		//Calcular en número de secuencia en función de la posición en la lista de secuencias del timeline
		var seqNumber = $(obj).parents('.sequence').prevAll().length;
		
		actionController.openEditWindow(seqNumber, action, actionID);
	}
	
	function _deleteAction(obj){
		
		var actionID = $(obj).parent().attr('id');
		var remove = leftTree.removeAction(actionID);
		
		$(obj).parent().remove();
		
		if (!remove){
			window.console.log('ERROR. Ninguna acción con el identificador ' + actionID);
			return false;
		}
		
		
	}
	
	
	function _hide(){
		
		var leaf = leftTree.selected();
		
		$('#show-timeline').parents('#timeline-btn').hide();
		_$wrapperBox.hide();
		_$addButton.hide();
		if(leaf && leaf.timeline){
			leaf.timeline.hide();
		}
	}
	
	
	function _show(){
		
		var leaf = leftTree.selected();
		
		_$wrapperBox.html(leaf.timeline);
		_$wrapperBox.show();
		_$addButton.show();
		
		if(leaf && leaf.timeline){
			leaf.timeline.show();
		}
		
		$.each(leaf.timeline.find(".sequence"), function(i,e){
			$(e).find(".addAction").click(function(){
				actionController.openWindow(i);
			});
			$(e).find(".deleteSequence").click(function(){
				window.console.log("deleting Sequence: "+i);
				_deleteSequence(i);
			});	
		});		
	}
	
	
	function _addSequence(){
		
		var	  leaf = leftTree.selected()
			, _$timeline = null
			, _$tmpSequence = $(_TMPL_sequence)
			, _guid = GUID()
			;
		
		if(leaf.timeline){
			_$timeline = leaf.timeline;
		}
		
		if(leaf.sequences){
			var _sequences = leaf.sequences
		}else{
			_sequences = [];
		}

		var _idSq = _sequences.length;

		_$tmpSequence.attr("id", _guid);
		
		_createKendoRepeatSequence(_$tmpSequence, _idSq);
		
		_$timeline.append(_$tmpSequence[0]);
		
		_$timeline.find("#"+_guid+" .addAction").click(function(){
			actionController.openWindow(_idSq);
		});
		
		_$timeline.find("#"+_guid+" .deleteSequence").click(function(){
			_deleteSequence(_idSq);
		});
		
		_sequences.push({idSq: _idSq, domObj : _$timeline.find("#"+_guid), actions : [], repeat: 0});		
		
		leaf.sequences = _sequences;
		leaf.timeline = _$timeline;
	}
	
	
	function _createKendoRepeatSequence(_$tmpSequence, _idSq, p_value){
		
		//repeat sequence numeric input
		_$tmpSequence.find('.repeatSequence').kendoNumericTextBox({
			decimals: 0,
			step: 1,
			format: "#",
			value: p_value || 0, 
			min: -1,
			upArrowText: "repetir secuencia",
			downArrowText: "repetir secuencia",
			change: function(e){
				
				_onChange(e, _idSq);
			}
		}).data("kendoNumericTextBox");
		
		_$tmpSequence.find('.k-numerictextbox').css('margin-top', '-17px');
	}
	
	
	function _onChange(e, idSq){
		
		var value = e.sender.value()
		  , seq = leftTree.selected().sequences[idSq]
		
		if(seq){
			seq.repeat = value;
		}
		
	}
	
	
	
	function _addAction(p_idSq, p_nameAction, p_duration){
		
		var	  leaf = leftTree.selected()
			, _$timeline = null
			, _$tmpAction = $(_TMPL_action)
			, _guid = GUID()
			, _baseColour = 3
			, _sequences = null
			;
		
		if(leaf.timeline){
			_$timeline = leaf.timeline;
		}else{
			_$timeline = $(_TMPL_timeline);
		}
		
		if(leaf.sequences){
			_sequences = leaf.sequences
		}else{
			_sequences = [];
		}
		
		_$tmpAction.attr("id", _guid);
		_sequences[p_idSq].domObj.find(".sequenceContainer").append(_$tmpAction[0]);	
		_sequences[p_idSq].domObj.find("#"+_guid+" .edit-action").html(p_nameAction);
		_sequences[p_idSq].actions.push({idAction: _guid, duration:p_duration, action : leaf.actions[p_nameAction], domObj : _$timeline.find("#"+_guid)});
		
		
		for(j=0; j < _sequences.length; j++){		
			
			var _sequenceWidth = 0;
			
			for(i = 0; i< _sequences[j].actions.length; i++){
				
				if((_sequences[j].actions[i].duration / 50) > 20 ){
					_actionWidth = (_sequences[j].actions[i].duration / 100);
				}

				$(_sequences[j].actions[i].domObj).data("i",i);
				$(_sequences[j].actions[i].domObj).data("j",j);
			}
			
			var actionWidth = _sequences[j].domObj.find(".actions").outerWidth(true);
			var actionLength = _sequences[j].domObj.find(".actions").length;
			var addActionWidth = _sequences[j].domObj.find(".addAction").outerWidth(true);
			
			var sequenceContainerInnerWidth = actionWidth * actionLength + addActionWidth
			
			_sequences[j].domObj.find(".sequenceContainer").width( sequenceContainerInnerWidth );
			
			var sequenceContainerOuterWidth = _sequences[j].domObj.find(".sequenceContainer").outerWidth(true);
			var trashWidth = _sequences[j].domObj.find(".toolbar").outerWidth(true);
			
			_sequences[j].domObj.width( sequenceContainerOuterWidth + trashWidth );
		}
		
		leaf.sequences = _sequences;
		leaf.timeline = _$timeline;
		
	}//end _addAction function
	
	
	function _addEditedAction(p_idSq, p_nameAction, p_duration, p_idAction){
		
		var	  leaf = leftTree.selected()
			, _$timeline = null
			, _$tmpAction = $(_TMPL_action)
			, _guid = GUID()
			, _baseColour = 3
		;
		
		_$timeline = leaf.timeline;
		_sequences = leaf.sequences;
		
		_sequences[p_idSq].domObj.find("#"+p_idAction+" .edit-action").html(p_nameAction);
		
		//Modificamos la acción existente
		$.each(_sequences[p_idSq].actions, function(i, e){
			
			if (e.idAction == p_idAction) {
				
				e.duration = p_duration,
				e.action = leaf.actions[p_nameAction]
				domObj : _$timeline.find("#"+p_idAction)
			}
		})

		
	}//end _editAction function
	
	
	function _updateSequences(){
	
		var	  leaf = leftTree.selected()
			, _$timeline = null
			, _$tmpSequence = null
			, _$tmpAction = null
			, _baseColour = 3
		;
	
		if(leaf.timeline){
			_$timeline = leaf.timeline;
		}else{
			_$timeline = $(_TMPL_timeline);
		}
		_$timeline = $(_TMPL_timeline);
		
	
		if(leaf.sequences){
			var _sequences = leaf.sequences
		}else{
			_sequences = [];
		}
	
		
		for(var j=0; j < _sequences.length; j++){		
			
			var _guid = GUID();
			
			_$tmpSequence = $(_TMPL_sequence);
			
			_$tmpSequence.attr("id", _guid);	
			
			_createKendoRepeatSequence(_$tmpSequence, j, _sequences[j].repeat);
			//_$tmpSequence.find('.repeatSequence').val( _sequences[j].repeat )

			_$timeline.append(_$tmpSequence[0]);
			
			_$timeline.find("#"+_guid+" .addAction").attr('pos', j);
			_$timeline.find("#"+_guid+" .addAction").click(function(){
				actionController.openWindow( $(this).attr('pos') );
			});
			
			_$timeline.find("#"+_guid+" .deleteSequence").attr('pos', j);
			_$timeline.find("#"+_guid+" .deleteSequence").click(function(){
				_deleteSequence( $(this).attr('pos') );
			});
			
			_sequences[j].domObj = _$timeline.find("#"+_guid);
			
			var _sequenceWidth = 0;
			
			for(i = 0; i< _sequences[j].actions.length; i++){
				
				var _guid = GUID();
				
				_$tmpAction = $(_TMPL_action);
				
				_$tmpAction.attr("id", _guid);
				
				_sequences[j].domObj.find(".sequenceContainer").append(_$tmpAction[0]);	
				_sequences[j].domObj.find("#"+_guid+" .edit-action").html(leaf.sequences[j].actions[i].action.name);
				_sequences[j].actions[i].domObj = _$timeline.find("#"+_guid);
				_sequences[j].actions[i].idAction = _guid;
				
				_sequences[j].actions[i].duration = _sequences[j].actions[i].action.duration;
				
				if((_sequences[j].actions[i].duration / 50) > 20 ){
					_actionWidth = (_sequences[j].actions[i].duration / 100);
				}

				$(_sequences[j].actions[i].domObj).data("i",i);
				$(_sequences[j].actions[i].domObj).data("j",j);
				_sequences[j].actions[i].domObj.unbind("click").click(function(e){
					window.console.log("clicking action");
				});						
			}
			
			var actionWidth = _sequences[j].domObj.find(".actions").outerWidth(true);
			var actionLength = _sequences[j].domObj.find(".actions").length;
			var addActionWidth = _sequences[j].domObj.find(".addAction").outerWidth(true);
			
			var sequenceContainerInnerWidth = actionWidth * actionLength + addActionWidth
			
			_sequences[j].domObj.find(".sequenceContainer").width( sequenceContainerInnerWidth );
			
			var sequenceContainerOuterWidth = _sequences[j].domObj.find(".sequenceContainer").outerWidth(true);
			var trashWidth = _sequences[j].domObj.find(".toolbar").outerWidth(true);
			
			_sequences[j].domObj.width( sequenceContainerOuterWidth + trashWidth );
			
		}
	
		leaf.timeline = _$timeline;
			
	}//end edit action
	
	
	function _deleteSequence(p_idSeq){
		
		var	  leaf = leftTree.selected()
			;
		
		leaf.timeline.find(".sequence:nth("+p_idSeq+")").remove();
		
		_show();
		
		if(leaf.sequences[p_idSeq]){
			leaf.sequences.splice(p_idSeq,1);
		}
		
		if(_sequences[p_idSeq]){
			_sequences.splice(p_idSeq,1);
		}
		
		
	}
	
	function _updateSequencesList(){
	
		var leaf = leftTree.selected();
		
		if (leaf){
			
			if(leaf.timeline){
				_show();
				_updateSequences();
				_$wrapperBox.html(leaf.timeline);
			}
			else{
				
				
				var _$timeline = $(_TMPL_timeline);
				_$wrapperBox.html(_$timeline);
				leaf.timeline = _$timeline;	
				
				_show();
				_updateSequences();
				_$wrapperBox.html(leaf.timeline);
			}
		}
	}	
	
	function GUID()	{
	    var S4 = function (){
	        return Math.floor(
	                Math.random() * 0x10000 /* 65536 */
	            ).toString(16);
	    };
	    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	}
	
	
	//comprobar si abrir ventana de timeline al cerrar ventana de preview
	function _ReOpen(){
		
		if(_lastSelectedObject && $('[data-uid="' + _lastSelectedObject + '"]')){
			
			$('[data-uid="' + _lastSelectedObject + '"] span').click()
			$("#timeline-window").data("kendoWindow").center().open();				
		}
		_lastSelectedObject = false;
		
		_updateSequencesList();
	}
	
	
	function showTimelineButton(){
		
		//el timeline solo es para objetos, no para grupos
		if (!mainCanvas.canvas.getActiveGroup()){
			$('#show-timeline').parents('#timeline-btn').show();	
		}
	}
	
		
	this.init = _init;
	this.AddSequence = _addSequence;
	this.AddAction = _addAction;
	this.AddEditedAction = _addEditedAction;
	this.Hide = _hide;
	this.sequences = _sequences;
	this.UpdateSequenceList = _updateSequencesList;
	this.ReOpen = _ReOpen;
	this.ShowTimelineButton = showTimelineButton;
	
}

